import java.awt.FlowLayout;
import java.awt.TextArea;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;

import javax.swing.JFrame;


public class Server extends UnicastRemoteObject implements Server_itf {
	
	private int nextId = 0;
	private HashMap<Integer, ServerObject> serverObjectsById = new HashMap<Integer, ServerObject>();
	private HashMap<String, ServerObject> serverObjectsByName = new HashMap<String, ServerObject>();
	private Object nextIdLock = new Object();
	
	
	public Server() throws RemoteException {
		super();
	}
	
	// invoked by Client
	public int create(Object o) throws RemoteException {
		int id = getId();
		ServerObject svo = new ServerObject(id, o);
		serverObjectsById.put(id, svo);
		return id;
	}// done

	public Object lock_read(int id, Client_itf client) throws RemoteException {
		return serverObjectsById.get(id).lock_read(client);
	}// done

	public Object lock_write(int id, Client_itf client) throws RemoteException {
		return serverObjectsById.get(id).lock_write(client);
	}// done

	// invoked by Client
	public int lookup(String name) throws RemoteException {
		ServerObject svo = serverObjectsByName.get(name);
		if (svo == null) {
			return -1;
		}
		else {
			return svo.id;
		}
	}
	
	// invoked by Client
	public void register(String name, int id) throws RemoteException {
		ServerObject svo = serverObjectsById.get(id);
		serverObjectsByName.put(name, svo);
	}
	
	private int getId() {
		synchronized(nextIdLock ) {
			return nextId++;
		}
	}// done
	
	public static void main(String[] args) {
		try {
			LocateRegistry.createRegistry(1099);
			Server s = new Server();
			Naming.rebind("myServer", s);
			System.out.println("Serveur lanc� sur 1099");
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}

	// -------------------------->  Ajout etape 2 <--------------------------
	public Object getObjNotSynchronised(int id) throws RemoteException {
		return serverObjectsById.get(id).getObjNotSynchronised();
	}

}
